package org.familysearch.fsapi.gwt.server.bo;

import java.util.ArrayList;

import org.apache.log4j.Logger;
import org.familysearch.fsapi.gwt.common.client.entities.Person;
import org.familysearch.fsapi.gwt.common.client.entities.Temple;
import org.familysearch.fsapi.gwt.server.dao.DAOException;
import org.familysearch.fsapi.gwt.server.dao.DAOFactory;
import org.familysearch.fsapi.gwt.server.dao.PersonDAO;
import org.familysearch.fsapi.gwt.server.dao.Session;
import org.familysearch.fsapi.gwt.server.dao.TempleDAO;

public class PersonBO {

	private IdentityBO identityBO = new IdentityBO();
	private DAOFactory daoFactory = DAOFactory.instance(DAOFactory.REST);
	private PersonDAO personDAO;
	private Logger log;
	
	
	public PersonBO()
	{
		personDAO = daoFactory.getPersonDAO();
		log = Logger.getLogger(this.getClass().getName());
	}
	
	private void auth() throws BOException
	{
		Session session = identityBO.initializeSession();
		personDAO.setSession(session);
	}
	
	public Person getPerson(Person person) throws BOException
	{
		// authenticate first
		auth();
		
		// temple cannot be null
		if( person == null )
		{
			throw new BOException("bad", "bad"); // TODO set proper exception
			
		}
		
		if( person.getId() == null ||
				person.getId().equalsIgnoreCase( "" ))
		{
			throw new BOException("BO-0002", "Please set person ID in order to fetch the person"); // TODO set proper exception
		}
		
		Person fetched = null; 
		try {
			fetched = personDAO.findById(person.getId());
		} catch (DAOException e) {
			// TODO swallow and log DAOException but throw BOException
			log.error(e.toString());
			throw new BOException("B0-0004", "No person fetched due to DAO error. Please check logs."); // TODO set proper exception			
		}
		
		if( fetched == null )
		{
			throw new BOException("B0-0004", "No person fetched."); // TODO set proper exception
		}
		
		return fetched;
		

	}
	
}
